package com.qsw.paper.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qsw.paper.constant.JwtClaimsConstant;
import com.qsw.paper.properties.JwtProperties;
import com.qsw.paper.utils.JwtUtil;
import com.qsw.paper.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * jwt令牌 管理员拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token = request.getHeader(jwtProperties.getTokenName());
        try {
            log.info("管理员token检验：{}", token);
            Claims claims = JwtUtil.parseToken(jwtProperties.getAdminSecretKey(), token);
            Integer adminId = Integer.parseInt(claims.get(JwtClaimsConstant.EMP_ID).toString());
            ThreadLocalUtil.setId(adminId);
            log.info("当前管理员id:{}", adminId);
            return true;
        } catch (Exception e) {
            log.error("资源访问失败", e);
            //4、不通过，响应401状态码
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Map.of("code", response.getStatus(), "msg", request.getRequestURI() + " 访问资源失败，请重试")));
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
